#!/bin/sh

. $(dirname $0)/adc.common-functions

[ -z "$GL_RC" ] && die "ENV GL_RC not set"
[ -z "$2" ] && die "Usage: fork source_repo target_repo"

# all the can_* functions set $repo
can_read $1 || die "no read permissions on $repo"
from=$repo

can_create $2 || die "no create permissions on $repo"
to=$repo

# clone $from to $to
git clone --bare -l $GL_REPO_BASE_ABS/$from.git $GL_REPO_BASE_ABS/$to.git
[ $? -ne 0 ] && exit 1

echo "$from forked to $to"

# fix up creator, gitweb owner, and hooks
cd $GL_REPO_BASE_ABS/$to.git
echo $GL_USER > gl-creater
git config gitweb.owner "$GL_USER"
( $GL_BINDIR/gl-query-rc GL_WILDREPOS_DEFPERMS ) |
    SSH_ORIGINAL_COMMAND="setperms $to" $GL_BINDIR/gl-auth-command $GL_USER
cp -R $GL_REPO_BASE_ABS/$from.git/hooks/* $GL_REPO_BASE_ABS/$to.git/hooks

if [ -n "$GL_WILDREPOS_DEFPERMS" ]; then
  echo "$GL_WILDREPOS_DEFPERMS" > gl-perms
fi

echo "$from" > gl-forked-from

# run gitolite's post-init hook if you can (hook code expects GL_REPO to be set)
export GL_REPO; GL_REPO="$to"
[ -x hooks/gl-post-init ] && hooks/gl-post-init
